package com.zj.osm.view.home.home.home_fragment.onefragment;

import android.Manifest;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.location_library.map.MapUtil;
import com.google.android.gms.common.util.DataUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;
import com.zj.mvplce.utils.permisson.PermissionXUtils;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.adapter.ProjectAdapter;
import com.zj.osm.bean.Filter;
import com.zj.osm.bean.LocalSelectedEnum;
import com.zj.osm.entity.db.ProjectDao;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.mvp.MvpFragment;
import com.zj.osm.view.home.home.GoFramgent;
import com.zj.osm.view.home.home.HomeActivity;
import com.zj.osm.view.homepage.ZipActivity;
import com.zj.osm.view.map.map.MapActivity;
import com.zj.osm.view.map.offline.OfflineMapActivity;
import com.zj.osm.view.project.addproject.AddProjectActivity;
import com.zj.utils.data.LiveDataBus;
import com.zj.utils.utils.http.HttpConfig;
import com.zj.utils.utils.utilcode.SPUtils;
import com.zj.utils.utils.utilcode.TimeUtils;
import com.zj.utils.utils.utilcode.ToastUtils;
import com.zj.utils.view.TitleBar;

import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

import static com.zj.osm.utils.Configuration.PROJECT_ID;

public class OneFragment extends MvpFragment<OneFragmentView, OneFragmentPresenter> implements View.OnClickListener, OneFragmentView, ProjectAdapterInterface {
    public static boolean DIALOG_BOTTOM = true;
    private List<Integer> images = new ArrayList<>();
    private TitleBar mHomeTitlebar;
    private ListView mProjectRv;
    ProjectAdapter projectAdapter;
    private List<Project> allprojectLis = new ArrayList<>();
    private TextView mPtCountTv;
    private TextView mOne_btn_two;
    private GoFramgent goFramgent;

    @Override
    public OneFragmentPresenter createPresenter() {
        return new OneFragmentPresenter();
    }

    @Override
    public OneFragmentView createView() {
        return this;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.one_fragment_lt;
    }

    @Override
    protected void initView(@NotNull View view) {
        super.initView(view);
        goFramgent = (GoFramgent) getActivity();
        long timeEnd= SPUtils.getInstance().getLong("firstTime")+30*24*60*60*1000L;
//        if (System.currentTimeMillis() -timeEnd > 0) {
//            final AlertDialog.Builder normalDialog = new AlertDialog.Builder(getActivity());
//            normalDialog.setTitle("试用期已到");
//            normalDialog.setMessage("请联系渤海新能官方或者客服获取正版App");
//            normalDialog.setPositiveButton("确定",
//                    (dialog, which) -> {
//                      dialog.dismiss();
//                      getActivity().finish();
//                    });
//            normalDialog.show();
//        } else {
//
//        }
        initViews(view);
        initBannerView(view);
        initOnclickView(view);
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            loadData();
            DIALOG_BOTTOM = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadData() {
        getPresenter().getProjectListData();
    }

    @Override
    public void allProjectList(List<Project> projectList) {
        allprojectLis.clear();
        if (!projectList.isEmpty()) {//获取最后一个[最新的一个]
            allprojectLis.add(projectList.get(projectList.size() - 1));
        }
        List<Project> list = App.getInstances().getDaoSession().getProjectDao().queryBuilder().orderDesc(ProjectDao.Properties.Id).build().list();
        mPtCountTv.setText(StringUtils.join("当前共有 ", list.size(), " 个项目"));
        projectAdapter.notifyDataSetChanged();
    }

    private void initViews(View view) {
        mHomeTitlebar = view.findViewById(R.id.homeTitlebar);
        mPtCountTv = view.findViewById(R.id.one_tv_count);
        mOne_btn_two = view.findViewById(R.id.one_btn_two);
        mOne_btn_two.setOnClickListener(this);
        mHomeTitlebar.setTitle(getString(R.string.bpp_name));
        mProjectRv = view.findViewById(R.id.one_listView);
        projectAdapter = new ProjectAdapter(this, allprojectLis);
        mProjectRv.setAdapter(projectAdapter);

    }

    private void initOnclickView(View view) {
        TextView[] textViews = new TextView[]{view.findViewById(R.id.one_btn_one), view.findViewById(R.id.one_btn_two), view.findViewById(R.id.one_btn_three), view.findViewById(R.id.one_btn_four), view.findViewById(R.id.one_btn_five), view.findViewById(R.id.one_btn_six), view.findViewById(R.id.one_btn_seven), view.findViewById(R.id.one_btn_eight)};
        for (TextView onclickView : textViews) {
            onclickView.setOnClickListener(this);
        }
        mProjectRv.setOnItemClickListener((parent, views, position, id) -> {
            Project items = (Project) projectAdapter.getItem(position);
            if (items.getState().equals("在线")) {
                //getToast(context, items.getName() + items.getId() + items.isCheck());
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("surverytaskid", items.getProjectId());
                String result = HttpConfig.callService(1, "getProjectStatusInfo", map);
                if (parseXMLWithPulls(result)) {
                    ToastUtils.showShort("此项目已结束勘测");
                } else {
                    LiveDataBus.get().getChannel(PROJECT_ID).setValue(items.getId());
                    Intent intent = new Intent(getContext(), MapActivity.class);
                    intent.putExtra("name", items.getState());
                    intent.putExtra("id", items.getId());
                    startActivity(intent);
                }
            } else {
                Log.e("projectIdOne==", items.getId().toString());
                LiveDataBus.get().getChannel(PROJECT_ID).setValue(items.getId());
                Intent intent = new Intent(getContext(), MapActivity.class);
                intent.putExtra("name", items.getState());
                intent.putExtra("id", items.getId());
                startActivity(intent);
            }

        });
    }

    //用Pull方式解析XML
    public static Boolean parseXMLWithPulls(String xmlData) {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            //设置输入的内容
            xmlPullParser.setInput(new StringReader(xmlData));
            //获取当前解析事件，返回的是数字
            int eventType = xmlPullParser.getEventType();
            //保存内容
            String code;

            while (eventType != (XmlPullParser.END_DOCUMENT)) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    //开始解析XML
                    case XmlPullParser.START_TAG: {
                        //nextText()用于获取结点内的具体内容
                        if ("date".equals(nodeName)) {
                            code = xmlPullParser.nextText();
                            if (code.equals("1"))
                                return true;
                        }

                    }
                    break;
                    //结束解析
                    case XmlPullParser.END_TAG: {
                    }
                    break;
                    default:
                        break;
                }
                //下一个
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void initBannerView(View view) {
        images.add(R.drawable.img_banner);
        images.add(R.mipmap.img_banner1);
        images.add(R.mipmap.img_banner2);
        Banner banner = view.findViewById(R.id.banner);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置轮播时间
        banner.setDelayTime(4000);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.one_btn_one:

                break;
            case R.id.one_btn_two:
                goFramgent.gotoFragment();
                break;
            case R.id.one_btn_three: {
                PermissionXUtils.INSTANCE.getPermission(
                        Objects.requireNonNull(getActivity()),
                        this::gotoOffLineMapActivity,
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.ACCESS_FINE_LOCATION);
                //.latitude(40.05087)
                //    .longitude(116.30142)
                // .latitude(39.90882)
                //.longitude(116.39750)
                //百度导航结果
                //MapUtil.startNaviDialog((Activity)getContext(),"40.05087","116.30142","百度大厦","39.90882","116.39750","北京天安门");
                break;
            }
            case R.id.one_btn_four://新建项目部分
                Intent intent = new Intent(getContext(), AddProjectActivity.class);
                startMyActivity(intent);
                break;
            case R.id.one_btn_five:

                break;
            case R.id.one_btn_six:
                Intent intents = new Intent(getContext(), ZipActivity.class);
                startMyActivity(intents);
                break;
            case R.id.one_btn_seven:

                break;
            case R.id.one_btn_eight:

                break;
            case R.id.oneRlItemList://当前共有多少项目
                break;
        }
    }

    private void gotoOffLineMapActivity() {
        startMyActivity(new Intent(getContext(), OfflineMapActivity.class));
    }

    @Override
    public void initListener() {

    }

    @Override
    public void getProjectList() {
        loadData();
    }


    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            imageView.setImageResource((Integer) path);
        }

        //提供createImageView 方法，如果不用可以不重写这个方法，主要是方便自定义ImageView的创建
        @Override
        public ImageView createImageView(Context context) {
            //使用fresco，需要创建它提供的ImageView，当然你也可以用自己自定义的具有图片加载功能的ImageView
            return new ImageView(context);
        }
    }


    @Override
    public void setAsc() {

    }

    @Override
    public void setDesc() {

    }

    @Override
    public void setOtherOrder(LocalSelectedEnum selectWhere, Filter filter) {

    }

    @Override
    public void setGuanliListItem(int visible, boolean ischeck) {

    }
}
